package com.cy.bean.spider;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.cy.service.news.NewsService;

import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.Pipeline;

/**
 * 爬虫工具类
 * @author CY
 *
 */
@Component
public class SpiderUtils {

	@Resource
	private Pipeline pipeline;
	private Spider spider = null;
	private boolean isStart = false;
	private Timer timer = null;
	
	/**
	 * 开启爬虫
	 * @param date
	 * @param interval
	 */
	public void start(Date date, Long interval) {
		if(isStart) {
			throw new RuntimeException("爬虫已经启动");
		}
        timer = new Timer();
        timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(spider != null) {
					spider.stop();
				}
				 spider = Spider.create(new NewsSpider())
		        .addUrl("http://news.ycw.gov.cn/html/node_91289.htm")
		        .addPipeline(pipeline);
		        ((NewsService)pipeline).setSpider(spider);
		        spider.thread(5).start();
		        System.out.println("爬虫开启"+new Date());
		        isStart = true;
			}
		}, date, interval);
    }
	
	/**
	 * 关闭爬虫
	 */
	public void stop() {
		if(!isStart) {
			throw new RuntimeException("爬虫没有启动");
		}
		spider.stop();
		spider = null;
		timer.cancel();
		isStart = false;
	}
	
	/**
	 * 爬虫是否运行
	 * @return
	 */
	public boolean isStart() {
		return isStart;
	}
}
